<template>
  <div class='ele-body ele-body-card'>
    <!-- 顶部卡片 -->
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='form'
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='checkAndPushSubmitConfig'
      >
        <a-divider orientation="left">基础设置</a-divider>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label="Model:" name="cfMode">
              <a-select v-model:value="form.cfMode">
                <a-select-option :value="0">Disable</a-select-option>
                <a-select-option :value="1">Fixed Timing Report</a-select-option>
                <a-select-option :value="2">Fixed Distance Report</a-select-option>
                <a-select-option :value="3">Fixed Mileage Report</a-select-option>
                <a-select-option :value="4">Optimum Report</a-select-option>
                <a-select-option :value="5">Fixed Time or Mileage Report</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Send Interval(秒):' name='sendInterval'>
              <a-input-number :min="0" :max="86400" v-model:value='form.sendInterval' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='IGF Report Interval(秒):' name='igfReportInterval'>
              <a-input-number :min="0" :max="86400" v-model:value='form.igfReportInterval' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Check Interval(秒):' name='checkInterval'>
              <a-input-number :min="0" :max="86400" v-model:value='form.checkInterval' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label="Wrap Corner Point" name="wrapCornerPoint">
              <a-select v-model:value="form.wrapCornerPoint">
                <a-select-option :value="0">Do not wrap corner point</a-select-option>
                <a-select-option :value="1">Wrap corner point and wait</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-divider orientation="left">Report Period Setting</a-divider>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label="Period" name="enablePeriod">
              <a-select v-model:value="form.enablePeriod">
                <a-select-option :value="0">disable</a-select-option>
                <a-select-option :value="1">enable</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Start Time(HHMM):' name='startTime'>
              <a-input v-model:value='form.startTime' placeholder='请输入开始时间' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='End Time(HHMM):' name='endTime'>
              <a-input v-model:value='form.endTime' placeholder='请输入结束时间' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-divider orientation="left">Mileage Setting</a-divider>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Distance(meters):' name='distance'>
              <a-input-number :min="50" :max="65535" v-model:value='form.distance' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Mileage(meters):' name='mileage'>
              <a-input-number :min="50" :max="65535" v-model:value='form.mileage' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-divider orientation="left">Other Setting</a-divider>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label="Discard No Fix" name="discardNoFix">
              <a-select v-model:value="form.discardNoFix">
                <a-select-option :value="0">disable</a-select-option>
                <a-select-option :value="1">enable</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Corner Report(degree):' name='cornerReport'>
              <a-input-number :min="0" :max="180" v-model:value='form.cornerReport' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='Eri Mask:' name='eriMask'>
              <a-checkbox v-model:checked="eriMaskCheck.fuelsensor">for the Digital Fuel Sensor Data field in +RESP:GTERI</a-checkbox>
              <a-checkbox v-model:checked="eriMaskCheck.wire">for the 1-Wire Data field in +RESP:GTERI</a-checkbox>
              <a-checkbox v-model:checked="eriMaskCheck.can">for the Can Data field in +RESP:GTERI</a-checkbox>
              <a-checkbox v-model:checked="eriMaskCheck.percentage">for the Percentage field in +RESP:GTERI</a-checkbox>
              <a-checkbox v-model:checked="eriMaskCheck.volume">for the Volume field in +RESP:GTERI</a-checkbox>
              <a-checkbox v-model:checked="eriMaskCheck.rf433">for the RF433 Accessory Data field in +RESP:GTERI</a-checkbox>
              <a-checkbox v-model:checked="eriMaskCheck.bluetooth">for the Bluetooth Acessory Data field in +RESP:GTERI</a-checkbox>
              <a-checkbox v-model:checked="eriMaskCheck.fueltemperature">for the Fuel Temperature field in +RESP:GTERI</a-checkbox>
              <a-checkbox v-model:checked="eriMaskCheck.rs485">for the RS485 Sensor Data field in +RESP:GTERI</a-checkbox>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='2' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'>
            <a-button type='primary' html-type='submit' :loading='formSubmitLoading'>
              提交
            </a-button>
            <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='readGTSPD' :loading='readLoading'>
              读取
            </a-button>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='6' :sm='24' :xs='24'></a-col>
        </a-row>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import {VehicleConfigFriApi} from "@/api/property/vechile/VehicleConfigFriApi";

export default {
  name: 'DeviceVehicleConfigFri',
  components: {

  },
  props: {
    data: Object
  },
  async created() {
    this.getDetail();
  },
  data() {
    return {
      form : {},
      currentConfig : {},
      eriMaskCheck : {},
      loading : false,

      formSubmitLoading : false,
      formSubmitTimer : undefined,

      readLoading : false,
      readTimer : undefined
    };
  },
  methods: {
    getDetail() {
      let that = this;
      VehicleConfigFriApi.detail({"recordId" : this.data.recordId}).then(result => {
        that.form = result || {};
        let eriMask = that.form.eriMask || 0;
        that.eriMaskCheck.fuelsensor = (eriMask & 1) == 1;
        that.eriMaskCheck.wire = ((eriMask >> 1) & 1) == 1;
        that.eriMaskCheck.can = ((eriMask >> 2) & 1) == 1;
        that.eriMaskCheck.percentage = ((eriMask >> 3) & 1) == 1;
        that.eriMaskCheck.volume = ((eriMask >> 4) & 1) == 1;
        that.eriMaskCheck.rf433 = ((eriMask >> 7) & 1) == 1;
        that.eriMaskCheck.bluetooth = ((eriMask >> 8) & 1) == 1;
        that.eriMaskCheck.fueltemperature = ((eriMask >> 10) & 1) == 1;
        that.eriMaskCheck.rs485 = ((eriMask >> 13) & 1) == 1;

        that.currentConfig = JSON.parse(JSON.stringify(result || {}));
      });
    },

    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail2(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //-------提交
    clearSubmitConfig(){
      this.formSubmitLoading = false;
      clearInterval(this.formSubmitTimer);
    },

    checkSubmitConfig(){
      let that = this;
      this.checkProcess(8, this.clearSubmitConfig, function(){
        that.getDetail();
      });
    },

    checkAndPushSubmitConfig() {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 8
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitConfigSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitConfigSubmit() {
      this.loading = true;
      let eriMask = this.eriMaskCheck.fuelsensor ? 1 : 0;
      if (this.eriMaskCheck.wire) {
        eriMask = eriMask | ((this.eriMaskCheck.wire ? 1 : 0) << 1);
      }
      if (this.eriMaskCheck.can) {
        eriMask = eriMask | ((this.eriMaskCheck.can ? 1 : 0) << 2);
      }
      if (this.eriMaskCheck.percentage) {
        eriMask = eriMask | ((this.eriMaskCheck.percentage ? 1 : 0) << 3);
      }
      if (this.eriMaskCheck.volume) {
        eriMask = eriMask | ((this.eriMaskCheck.volume ? 1 : 0) << 4);
      }
      if (this.eriMaskCheck.rf433) {
        eriMask = eriMask | ((this.eriMaskCheck.rf433 ? 1 : 0) << 7);
      }
      if (this.eriMaskCheck.bluetooth) {
        eriMask = eriMask | ((this.eriMaskCheck.bluetooth ? 1 : 0) << 8);
      }
      if (this.eriMaskCheck.fueltemperature) {
        eriMask = eriMask | ((this.eriMaskCheck.fueltemperature ? 1 : 0) << 10);
      }
      if (this.eriMaskCheck.rs485) {
        eriMask = eriMask | ((this.eriMaskCheck.rs485 ? 1 : 0) << 13);
      }
      this.form.eriMask = eriMask;

      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({ old: this.currentConfig, update: this.form}),
        dictate : 8, //AT+GTSPD=
        sceneDictate : 8 //SpeedAlarm
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.formSubmitLoading = true; //转圈
          this.formSubmitTimer = setInterval(this.checkSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },


    //----读取
    clearReadSubmitConfig(){
      this.readLoading = false;
      clearInterval(this.readTimer);
    },

    checkReadSubmitConfig(){
      let that = this;
      this.checkProcess(606, this.clearReadSubmitConfig, function(){
        that.getDetail();
      });
    },

    readGTSPD() {
      let workerDetailParams = {
        recordId: this.data.recordId,
        sceneDictate: 606
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailParams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitReadSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitReadSubmit() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({}),
        dictate : 606,
        sceneDictate : 606
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.readLoading = true; //转圈
          this.readTimer = setInterval(this.checkReadSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
